package edu.wuster.blog.service.impl;

import edu.wuster.blog.entity.Blogpart;
import edu.wuster.blog.entity.Collect;
import edu.wuster.blog.exception.MyException;
import edu.wuster.blog.mapper.BlogpartMapper;
import edu.wuster.blog.mapper.CollectMapper;
import edu.wuster.blog.mapper.UserMapper;
import edu.wuster.blog.service.CollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


//2024.3.16
//收藏模块已合并成点赞模块，部分函数已经用不上，现在已经优化成点赞接口

@Slf4j
@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private UserMapper userMapper;

    //收藏和点赞合并后的优化
    @Autowired
    private BlogpartMapper blogpartMapper;

    //查看收藏
    @Override
    public List<Collect> selectByUserId(Integer userId) {
        //非空判断
        if (userMapper.selectById(userId) == null) {
            throw new MyException("用户不存在");
        }
        return collectMapper.selectByUserId(userId);
    }

    //删除收藏（已经与点赞合并）
    @Override
    public void deleteById(Integer id) {
        //非空判断
        if (collectMapper.selectById(id) == null) {
            throw new MyException("被删除收藏不存在");
        }

        Collect collect = collectMapper.selectById(id);
        //点赞-1
        blogpartMapper.reduceLike(collect.getBlogId());

        //删除收藏
        collectMapper.deleteById(id);
    }

    //收藏模块已经优化成点赞
    @Override
    public Integer addCollect(Collect collect) {
        if (userMapper.selectById(collect.getUserId()) == null) {
            throw new MyException("用户不存在");
        }

        Collect collect1 = collectMapper.selectByBlogIdUserId(collect.getBlogId(),collect.getUserId());

        //判断曾经是否点赞过即is_delete是1
        if (collect1 == null) {
            //不存在记录
            Blogpart blogpart = blogpartMapper.selectById(collect.getBlogId());
            collect.setTitle(blogpart.getTitle());

            //新增记录
            collectMapper.addCollect(collect);
            blogpartMapper.addLike(collect.getBlogId());

            return collect.getId();

        } else if (collect1.getIsDelete() == 1) {
            //存在记录
            collectMapper.setIsDelete(collect1);
            blogpartMapper.addLike(collect1.getBlogId());
        }
        return collect1.getId();
    }
}
